import { createSlice, PayloadAction, createAsyncThunk } from '@reduxjs/toolkit';
import { getToken, setToken as setTokenToStorage, clearToken } from '@/utils';
import { loginApI, getPrfliileAPI } from '@/apis/user';

// 用户信息接口
interface UserInfo {
  id?: string;
  name?: string;
  avatar?: string;
  email?: string;
  // 可根据实际需求添加更多字段
}

// 登录表单类型
export interface LoginForm {
  mobile?: string;
  code?: string;
}

// 用户状态接口
export interface UserState {
  token: string;
  userInfo: UserInfo;
  loading: boolean;
  error: string | null;
}

const initialState: UserState = {
  token: getToken() || '',
  userInfo: {},
  loading: false,
  error: null
};

// 异步登录action
export const fetchLogin = createAsyncThunk<
  string, // 返回类型
  LoginForm, // 参数类型
  { rejectValue: string } // thunkAPI类型
>(
  'user/fetchLogin',
  async (loginForm: LoginForm, { rejectWithValue }) => {
    try {
      const res = await loginApI(loginForm);
      const token = res.data.token;
      setTokenToStorage(token);
      return token;
    } catch (error) {
      const message = error instanceof Error ? error.message : '登录失败';
      return rejectWithValue(message);
    }
  }
);

// 异步获取用户信息action
export const fetchUserInfo = createAsyncThunk<
  UserInfo, // 返回类型
  void, // 参数类型
  { rejectValue: string } // thunkAPI类型
>(
  'user/fetchUserInfo',
  async (_, { rejectWithValue }) => {
    try {
      const res = await getPrfliileAPI();
      return res.data;
    } catch (error) {
      const message = error instanceof Error ? error.message : '获取用户信息失败';
      return rejectWithValue(message);
    }
  }
);

const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    // 直接设置token
    setToken(state, action: PayloadAction<string>) {
      state.token = action.payload;
      setTokenToStorage(action.payload);
      state.error = null;
    },
    // 直接设置用户信息
    setUserInfo(state, action: PayloadAction<UserInfo>) {
      state.userInfo = action.payload;
      state.error = null;
    },
    // 清除用户信息
    clearUserInfo(state) {
      state.token = '';
      state.userInfo = {};
      state.loading = false;
      state.error = null;
      clearToken();
    },
    // 清除错误信息
    clearError(state) {
      state.error = null;
    }
  },
  extraReducers: (builder) => {
    // 处理登录
    builder
      .addCase(fetchLogin.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchLogin.fulfilled, (state, action) => {
        state.loading = false;
        state.token = action.payload;
        state.error = null;
      })
      .addCase(fetchLogin.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload || '登录失败';
      })
    // 处理获取用户信息
      .addCase(fetchUserInfo.pending, (state) => {
        state.loading = true;
        state.error = null;
      })
      .addCase(fetchUserInfo.fulfilled, (state, action) => {
        state.loading = false;
        state.userInfo = action.payload;
        state.error = null;
      })
      .addCase(fetchUserInfo.rejected, (state, action) => {
        state.loading = false;
        state.error = action.payload || '获取用户信息失败';
      });
  }
});

// 导出actions
export const { setToken, setUserInfo, clearUserInfo, clearError } = userSlice.actions;

// 选择器函数
export const selectUser = (state: { user: UserState }) => state.user;
export const selectToken = (state: { user: UserState }) => state.user.token;
export const selectUserInfo = (state: { user: UserState }) => state.user.userInfo;
export const selectUserLoading = (state: { user: UserState }) => state.user.loading;
export const selectUserError = (state: { user: UserState }) => state.user.error;

// 导出reducer
const userReducer = userSlice.reducer;
export default userReducer;